﻿using MediatR;
using MS.BasicData.Infrastructure;
using MS.BasicData.Infrastructure.IBaseRepository;
using System.ComponentModel.DataAnnotations;

namespace MS.BasicData.Read.API.Applications.Roles
{
    public class UpDateRoleRequestHandler : IRequestHandler<UpDateRoleRequestModel, ApiRestult>
    {
        /// <summary>
        /// 角色仓储
        /// </summary>
        private readonly IRoleBaseRepository _roleRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roleRepository"></param>
        public UpDateRoleRequestHandler(IRoleBaseRepository roleRepository)
        {
            _roleRepository = roleRepository;
        }

        public async Task<ApiRestult> Handle(UpDateRoleRequestModel request, CancellationToken cancellationToken)
        {

            ApiRestult restult = new ApiRestult
            {
                isSuc = true,
                Message = "更新角色成功",
                Code = Restult.Success
            };

            var role = await _roleRepository.GetAll(a => a.RoleId == request.RoleId);
            if (role == null)
            {
                restult.isSuc = false;
                restult.Message = "角色不存在";
                restult.Code = Restult.Fail;
                return restult;
            }
            role.RoleId = request.RoleId;
            role.RoleName = request.RoleName;
            role.Description = request.Description;
            await _roleRepository.UpdateAsync(role);

            return restult;
        }
    }

    public class UpDateRoleRequestModel : IRequest<ApiRestult>
    {
        /// <summary>
        /// 角色ID
        /// </summary>
        public int RoleId { get; set; }

        /// <summary>
        /// 角色名称
        /// </summary>
        public string RoleName { get; set; } = string.Empty;
        /// <summary>
        /// 角色描述
        /// </summary>
        public string Description { get; set; } = string.Empty;
    }
}
